import '@ant-design/compatible/assets/index.css';
import { Badge, Card, message, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import ContentModal from '../../../components/ContentModal';
import Ellipsis from '../../../components/Ellipsis';
import * as G from '../../../utils/common';

const mapStateToProps = (state: any) => ({
  handleLog: state.handleLog,
  loading: state.loading.models['handleLog'],
});

class HandleLog extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {
        startTime: moment()
          .add(-1, 'months')
          .format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      },
      paramsDetailVisible: false,
      paramsDetailModal: {},
      resultDetailVisible: false,
      resultDetailModal: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'handleLog/postFetchPage',
      payload: { url: '/log/handle/page', ...formValues },
    });
  }

  /**
   * 参数校验
   */
  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['handleTimeRange'];
      if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(1, 'months'))) {
        message.warning('操作时间区间为一个月！');
        return false;
      } else {
        return fields;
      }
    } else {
      message.warning('请选择操作时间！');
      return false;
    }
  };

  handleFormReset = () => {
    let startTime = moment()
      .add(-1, 'months')
      .format('YYYY-MM-DD HH:mm:ss');
    let endTime = moment().format('YYYY-MM-DD HH:mm:ss');
    this.searchForm.current.setFieldsValue({
      handleTimeRange: [moment(startTime), moment(endTime)],
    });
    this.setState({
      formValues: {
        startTime: startTime,
        endTime: endTime,
      },
    });
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      current,
      pageSize,
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'handleLog/postFetchPage',
      payload: { url: '/log/handle/page', ...params },
    });
  };

  handleDetailParams = (optParams: any) => {
    this.setState({
      paramsDetailModal: optParams,
      paramsDetailVisible: true,
    });
  };

  handleDetailResult = (optResult: any) => {
    this.setState({
      resultDetailModal: optResult,
      resultDetailVisible: true,
    });
  };

  render() {
    const {
      handleLog: {
        pageData: { list, pagination },
      },
      loading,
    } = this.props;
    const {
      paramsDetailModal,
      paramsDetailVisible,
      resultDetailModal,
      resultDetailVisible,
    } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 80,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '账号',
        dataIndex: 'accountName',
        width: 80,
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '模块',
        dataIndex: 'handleModule',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '方法',
        dataIndex: 'handleMethod',
        width: 170,
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '结果',
        dataIndex: 'handleResult',
        width: 80,
        render: (text: any) =>
          text === 0 ? (
            <Badge status="success" text="成功" />
          ) : text === 1 ? (
            <Badge status="warning" text="失败" />
          ) : text === 2 ? (
            <Badge status="error" text="异常" />
          ) : (
            <Badge status="default" text="未知" />
          ),
      },
      {
        title: '参数',
        dataIndex: 'handleParams',
        render: (text: any) => (
          <a onClick={() => this.handleDetailParams(text)}>
            <Ellipsis length={15}>{text}</Ellipsis>
          </a>
        ),
      },
      {
        title: '返回',
        dataIndex: 'handleResp',
        render: (text: any) => (
          <a onClick={() => this.handleDetailResult(text)}>
            <Ellipsis length={15}>{text}</Ellipsis>
          </a>
        ),
      },
      {
        title: '异常',
        dataIndex: 'handleException',
        render: (text: any) => {
          return (
            <Ellipsis length={15} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '时间',
        dataIndex: 'createDate',
        width: 150,
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '时间',
        type: 'rangePicker',
        customStyle: 10,
        key: 'handleTimeRange',
        initialValue: [
          moment(this.state.formValues.startTime),
          moment(this.state.formValues.endTime),
        ],
        rules: [{ required: true, message: '操作时间必选!' }],
      },
      {
        title: '账号',
        type: 'input',
        customStyle: 6,
        key: 'accountName',
      },
      {
        title: '模块',
        type: 'input',
        customStyle: 6,
        key: 'handleModule',
      },
      {
        title: '方法',
        type: 'input',
        key: 'handleMethod',
      },
      {
        title: '结果',
        type: 'select',
        selectOptions: [
          { value: '0', label: '成功' },
          { value: '1', label: '失败' },
          { value: '2', label: '异常' },
        ],
        key: 'handleResult',
      },
      {
        title: '参数',
        type: 'input',
        customStyle: 6,
        key: 'handleParams',
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'handleLog/postFetchPage',
              url: '/log/handle/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(this.state.formValues, val) })
            }
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: '100%' }}
          />
        </Card>
        <ContentModal
          title="操作入参详细信息"
          width="50%"
          changeVisible={() => this.setState({ paramsDetailVisible: false, paramsDetailModal: {} })}
          visible={paramsDetailVisible}
          formatData={true}
          detailModelData={paramsDetailModal}
        />
        <ContentModal
          title="操作返回详细信息"
          width="50%"
          changeVisible={() => this.setState({ resultDetailVisible: false, resultDetailModal: {} })}
          visible={resultDetailVisible}
          formatData={true}
          detailModelData={resultDetailModal}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(HandleLog);
